import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { errorResponse, successResponse, optionsResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';

async function handler(req: NextRequest) {
  let body: any;
  try {
    body = await req.json();
  } catch {
    return errorResponse('请求体需为 JSON', 400);
  }

  const { menuCode } = body || {};
  if (!menuCode || typeof menuCode !== 'string') {
    return errorResponse('缺少 menuCode', 400);
  }

  try {
    const menu = await prisma.menu.findFirst({ where: { sysCode: menuCode } });
    if (!menu) {
      return errorResponse('指定的菜单不存在', 404);
    }

    const categories = await prisma.category.findMany({
      where: { menuId: menu.id },
      include: {
        contents: {
          include: {
            content: {
              select: { title: true, url: true }
            }
          }
        }
      },
      orderBy: { createdAt: 'asc' }
    });

    const result = categories.map((cat) => ({
      name: cat.name,
      contents: cat.contents
        .map((cc) => cc.content)
        .filter((c) => !!c)
        .map((c) => ({ title: c!.title, url: c!.url || null }))
    }));

    return successResponse({
      menu: { id: menu.id, name: menu.name, code: menu.sysCode || null },
      categories: result
    });
  } catch (e: any) {
    console.error('查询失败:', e);
    return errorResponse(`查询失败: ${e.message}`, 500);
  }
}

export const POST = withMiddleware(handler);
export async function OPTIONS() { return optionsResponse(); }